package cn.pconline.officialclub.web.admin;

import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.service.AppConfigService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.IntfService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.RegionUtil;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.officialclub.entity.OClub;
import cn.pconline.officialclub.entity.OClubContact;
import cn.pconline.officialclub.entity.OClubTag;
import cn.pconline.officialclub.entity.OCommonMember;
import cn.pconline.officialclub.entity.OForum;
import cn.pconline.officialclub.service.OClubService;
import cn.pconline.officialclub.service.OClubTagService;
import cn.pconline.officialclub.service.OMemberService;
import com.alibaba.fastjson.JSONObject;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.gelivable.auth.entity.GeliSession;
import org.gelivable.auth.entity.GeliUser;
import org.gelivable.web.Env;
import org.gelivable.web.EnvUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author ppc
 */
@Controller
@RequestMapping(value = "/admin/brand/club")
public class AdminOClubController extends AdminControllerKit {

    @Autowired
    private OClubService oClubService;
    @Autowired
    private ClubService clubService;
    @Autowired
    private OMemberService oMemberService;
    @Autowired
    private AppConfigService appConfigService;
    @Autowired
    private OClubTagService oClubTagService;
    @Autowired
    private IntfService intfService;
    private static final String OCLUB_PRESIDENT_NAME = "OCLUB_PRESIDENT_ID";
    private static final Logger log = LoggerFactory.getLogger(AdminOClubController.class);

    /**
     * 查询品牌车友会
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/list.do")
    public String list(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        String orderField = env.param("orderField", "create_at");
        String orderDirection = env.param("orderDirection", "desc");
        String name = env.param("name", "").trim();
        String area = env.param("area", "").trim();//provinceName or cityName
        String brandName = env.param("brand", "").trim();
        String seriesName = env.param("series", "").trim();
        String beginString = env.param("beginDate", "");
        String endString = env.param("endDate", "");
        long oClubId = env.paramLong("oClubId", 0);
        String clubUrl = env.param("clubUrl", "");
        int pageNo = env.paramInt("pageNum", 1);
        int pageSize = env.paramInt("pageSize", 20);
        long regionId = env.paramLong("region", 0);
        int tagId = env.paramInt("tagId", OClub.STATUS_ALL);
        int status = WebUtils.paramInt(req, "status", OClub.STATUS_ALL);
        Date beginDate = DateUtils.parseDate(beginString, "yyyy-MM-dd HH:mm:ss");
        Date endDate = DateUtils.parseDate(endString, "yyyy-MM-dd HH:mm:ss");
        Pager<OClub> pager = oClubService.pageClubBy(oClubId, clubUrl, name, area, brandName, seriesName, regionId, beginDate, endDate, tagId, status, orderField, orderDirection, pageNo, pageSize);
        List<OClubTag> tags = oClubTagService.queryTags();
        if (pager != null) {
            oClubTagService.loadTags(pager.getResultList(), tags);
        }
        //return
        req.setAttribute("tags", tags);
        req.setAttribute("pager", pager);
        req.setAttribute("name", name);
        req.setAttribute("area", area);
        req.setAttribute("brand", brandName);
        req.setAttribute("series", seriesName);
        req.setAttribute("oClubId", oClubId);
        req.setAttribute("clubUrl", clubUrl);
        req.setAttribute("orderField", orderField);
        req.setAttribute("orderDirection", orderDirection);
        req.setAttribute("beginDate", beginDate);
        req.setAttribute("endDate", endDate);
        req.setAttribute("region", regionId);
        req.setAttribute("status", status);
        req.setAttribute("tagId", tagId);
        return "admin/official/club/list";
    }

    /**
     * 创建页面跳转
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/createClubPage.do", method = RequestMethod.GET)
    public String createClubPage(HttpServletRequest req, HttpServletResponse resp) {
        List<OClubTag> tags = oClubTagService.queryTags();
        req.setAttribute("tags", tags);
        return "admin/official/club/create";
    }

    /**
     * 创建品牌车友会
     *
     * @param req
     * @param resp w
     */
    @RequestMapping(value = "/create.do", method = RequestMethod.POST)
    public void create(HttpServletRequest req, HttpServletResponse resp) {
        //车友会信息
        String clubName = WebUtils.paramTrim(req, "name", "");
        String url = WebUtils.paramTrim(req, "url", "");
        long provinceId = WebUtils.paramLong(req, "provinceId", 0);
        long cityId = WebUtils.paramLong(req, "cityId", 0);
        String provinceName = WebUtils.param(req, "provinceName", "");
        int isBind = WebUtils.paramInt(req, "isbind", OClub.NOT_BIND_PHONE);
        if (provinceId == 0) {
            provinceName = "";
        }
        String cityName = WebUtils.getAreaPlaceByReq(req, "cityName", "");
        if (cityId == 0) {
            cityName = "";
        }
        long brandId = WebUtils.paramLong(req, "brandId", 0);
        long seriesId = WebUtils.paramLong(req, "seriesId", 0);
        String brandName = WebUtils.param(req, "brandName", "");
        if (brandId == 0) {
            brandName = "";
        }
        String seriesName = WebUtils.param(req, "seriesName", "");
        if (seriesId == 0) {
            seriesName = "";
        }
        int type = WebUtils.paramInt(req, "type", 0);
        long forumId = WebUtils.paramLong(req, "forumId", 0);
        String intr = WebUtils.param(req, "intr", "");
        long regionId = RegionUtil.getRegionId(provinceId);
        String regionName = RegionUtil.getRegionName(regionId);
        int status = WebUtils.paramInt(req, "status", OClub.STATUS_UNRELEASED);
        //商家信息
        String business = WebUtils.paramTrim(req, "business", "");
        String businessName = WebUtils.paramTrim(req, "businessName", "");
        String phone = WebUtils.param(req, "phone", "");
        String email = WebUtils.param(req, "email", "");
        String qq = WebUtils.param(req, "qq", "");
        String address = WebUtils.param(req, "address", "");
        String remark = WebUtils.param(req, "remark", "");
        GeliUser geliUser = GeliSession.getCurrentUser();
        if (geliUser == null) {
            errorMsg("请先登录", resp);
            return;
        }
        //表单校验 错误信息已在方法中返回
        if (!checkForm(req, resp, true)) {
            return;
        }
        //创建实体
        OClub oClub = new OClub();
        oClub.setName(clubName);
        oClub.setUrl(url);
        oClub.setProvinceId(provinceId);
        oClub.setProvinceName(provinceName);
        oClub.setCityId(cityId);
        oClub.setCoverImage("");
        oClub.setCityName(cityName);
        oClub.setBrandId(brandId);
        oClub.setBrandName(brandName);
        oClub.setSeriesId(seriesId);
        oClub.setSeriesName(seriesName);
        oClub.setForumId(forumId);
        oClub.setTagId(type);
        oClub.setCreateBy(geliUser.getUserId());
        oClub.setRegionId(regionId);
        oClub.setRegionName(regionName);
        oClub.setIntroduce(intr);
        oClub.setStatus(status);
        oClub.setBindPhone(isBind);
        long presidentId;
        String value = appConfigService.getValueByName(OCLUB_PRESIDENT_NAME);
        if (value == null) {
            errorMsg("创建失败:会长ID不存在", resp);
            return;
        }
        try {
            presidentId = Long.valueOf(value);
        } catch (NumberFormatException ex) {
            log.error("转换会长ID出错:" + value);
            errorMsg("创建失败:会长ID不存在", resp);
            return;
        }
        //默认有管理员
        oClub.setMemberNum(1);
        long clubId = oClubService.createClub(oClub);
        if (clubId > 0) {
            //创建商家信息
            OClubContact oClubContact = new OClubContact();
            oClubContact.setOClubId(clubId);
            oClubContact.setAddress(address);
            oClubContact.setBusiness(business);
            oClubContact.setCreateBy(geliUser.getUserId());
            oClubContact.setEmail(email);
            oClubContact.setQq(qq);
            oClubContact.setName(businessName);
            oClubContact.setPhone(phone);
            oClubContact.setRemark(remark);
            long oClubContactId = oClubService.createClubContact(oClubContact);
            if (oClubContactId > 0) {
                //创建会长
                OCommonMember oCommonMember = new OCommonMember();
                oCommonMember.setAdminType(OCommonMember.ADMIN_TYPE_PRESIDENT);
                oCommonMember.setJoinAt(new Date());
                oCommonMember.setOClubId(clubId);
                oCommonMember.setUserId(presidentId);
                long id = oMemberService.createCommonMember(oCommonMember);
                successMsg(resp, "list-oclub", "创建成功", "closeCurrent");
            } else {
                errorMsg("创建失败", resp);
            }
        }
    }

    /**
     * 修改页面
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/updatePage.do", method = RequestMethod.GET)
    public String updatePage(HttpServletRequest req, HttpServletResponse resp) {
        long oClubId = WebUtils.paramLong(req, "oClubId", 0);
        if (oClubId > 0) {
            OClub oClub = oClubService.findById(OClub.class, oClubId);
            if (oClub != null) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("o_club_id", oClubId);
                OClubContact oClubContact = oClubService.findUniqueLongKeyObject(OClubContact.class, map);
                List<OClubTag> tags = oClubTagService.queryTags();
                req.setAttribute("tags", tags);
                req.setAttribute("contact", oClubContact);
                req.setAttribute("o", oClub);
            }
        }
        return "admin/official/club/create";
    }

    /**
     * 修改
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/update.do", method = RequestMethod.POST)
    public void update(HttpServletRequest req, HttpServletResponse resp) {
        long oClubId = WebUtils.paramLong(req, "oClubId", 0);
        //车友会信息
        String clubName = WebUtils.param(req, "name", "");
        String url = WebUtils.param(req, "url", "");
        long provinceId = WebUtils.paramLong(req, "provinceId", 0);
        long cityId = WebUtils.paramLong(req, "cityId", 0);
        String provinceName = WebUtils.param(req, "provinceName", "");
        String cityName = WebUtils.getAreaPlaceByReq(req, "cityName", "");
        long brandId = WebUtils.paramLong(req, "brandId", 0);
        long seriesId = WebUtils.paramLong(req, "seriesId", 0);
        String brandName = WebUtils.param(req, "brandName", "");
        String seriesName = WebUtils.param(req, "seriesName", "");
        int type = WebUtils.paramInt(req, "type", 0);
        long forumId = WebUtils.paramLong(req, "forumId", 0);
        String intr = WebUtils.param(req, "intr", "");
        long regionId = RegionUtil.getRegionId(provinceId);
        String regionName = RegionUtil.getRegionName(regionId);
        int status = WebUtils.paramInt(req, "status", OClub.STATUS_UNRELEASED);
        //商家信息
        String business = WebUtils.param(req, "business", "");
        String businessName = WebUtils.param(req, "businessName", "");
        String phone = WebUtils.param(req, "phone", "");
        String email = WebUtils.param(req, "email", "");
        String qq = WebUtils.param(req, "qq", "");
        String address = WebUtils.param(req, "address", "");
        String remark = WebUtils.param(req, "remark", "");
        int isBind = WebUtils.paramInt(req, "isbind", OClub.NOT_BIND_PHONE);
        GeliUser geliUser = GeliSession.getCurrentUser();
        if (geliUser == null) {
            errorMsg("请先登录", resp);
            return;
        }
        //表单校验 错误信息已在方法中返回
        if (!checkForm(req, resp, false)) {
            return;
        }
        if (oClubId > 0) {
            OClub oClub = oClubService.findById(OClub.class, oClubId);
            if (oClub == null) {
                errorMsg("oClubId有误", resp);
                return;
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("o_club_id", oClubId);
            OClubContact oClubContact = oClubService.findUniqueLongKeyObject(OClubContact.class, map);
            if (oClubContact == null) {
                errorMsg("缺少商家信息", resp);
                return;
            }
            oClub.setProvinceId(provinceId);
            oClub.setProvinceName(provinceName);
            oClub.setCityId(cityId);
            oClub.setCityName(cityName);
            oClub.setBrandId(brandId);
            oClub.setBrandName(brandName);
            oClub.setSeriesId(seriesId);
            oClub.setSeriesName(seriesName);
            oClub.setForumId(forumId);
            oClub.setTagId(type);
            oClub.setCreateBy(geliUser.getUserId());
            oClub.setRegionId(regionId);
            oClub.setRegionName(regionName);
            oClub.setIntroduce(intr);
            oClub.setStatus(status);
            oClub.setBindPhone(isBind);
            int count = oClubService.updateClub(oClub);
            if (count > 0) {
                oClubContact.setOClubId(oClubId);
                oClubContact.setAddress(address);
                oClubContact.setBusiness(business);
                oClubContact.setCreateBy(geliUser.getUserId());
                oClubContact.setEmail(email);
                oClubContact.setQq(qq);
                oClubContact.setName(businessName);
                oClubContact.setPhone(phone);
                oClubContact.setRemark(remark);
                oClubService.updateClubContact(oClubContact);
                successMsg(resp, "list-oclub", "修改成功", "closeCurrent");
            } else {
                errorMsg("修改失败", resp);
            }

        } else {
            errorMsg("oClubId有误", resp);
        }
    }

    private boolean checkForm(HttpServletRequest req, HttpServletResponse resp, boolean checkNameAndUrl) {
        String clubName = WebUtils.paramTrim(req, "name", "");
        String url = WebUtils.paramTrim(req, "url", "");
        String business = WebUtils.paramTrim(req, "business", "");
        String intr = WebUtils.paramTrim(req, "intr", "");
        String remark = WebUtils.paramTrim(req, "remark", "");
        long forumId = WebUtils.paramLong(req, "forumId", 0);
        if (StringUtils.isBlank(clubName)) {
            errorMsg("车友会名称不能为空", resp);
            return false;
        }
        if (checkNameAndUrl) {
            if (oClubService.isNameExist(clubName)) {
                errorMsg("名称已被使用", resp);
                return false;
            }
            if (oClubService.isUrlExist(url)) {
                errorMsg("该域名已被使用", resp);
                return false;
            }
        }
        if (StringUtils.isBlank(business)) {
            errorMsg("商家信息不能为空", resp);
            return false;
        }
        if (StringUtils.isNotBlank(intr) && intr.length() > OClub.MAX_INTRODUCE_LENGTH) {
            errorMsg("简介超过最大长度", resp);
            return false;
        }
        if (StringUtils.isNotBlank(remark) && remark.length() > OClub.MAX_REMARK_LENGTH) {
            errorMsg("备注超过最大长度", resp);
            return false;
        }
        if (forumId == 0) {
            errorMsg("请输入关联论坛版块ID", resp);
            return false;
        }
        if (oClubService.findForum(forumId) == null) {
            JSONObject obj = intfService.findForumFromBbs(forumId);
            if(obj == null ){
                errorMsg("找不到该论坛版块", resp);
                return false;
            }
            OForum oForum = new OForum();
            oForum.setForumId(obj.getLong("fid"));
            oForum.setTitle(obj.getString("forumName"));
            String icon = obj.getString("forumIcon");
            oForum.setIcon(icon==null?"":icon);
            oForum.setUrl(obj.getString("forumUrl"));
            // 论坛接口已经转为车友会的type
            oForum.setType(obj.getIntValue("type"));
            long  id = oClubService.createOForum(oForum);
            if(id==0){
                return false;
            }
        }
        return true;
    }

    /**
     * 删除品牌车友会
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/delete.do", method = RequestMethod.POST)
    public void delete(HttpServletRequest req, HttpServletResponse resp) {
        errorMsg("不支持删除", resp);
    }

    /**
     * 创建页面跳转
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/batchJoinClubPage.do", method = RequestMethod.GET)
    public String batchJoinClubPage(HttpServletRequest req, HttpServletResponse resp) {
        return "admin/official/club/batchJoinClub";
    }

    /**
     * 创建品牌车友会
     *
     * @param req
     * @param resp w
     */
    @RequestMapping(value = "/batchJoinClub.do", method = RequestMethod.POST)
    public void batchJoinClub(HttpServletRequest req, HttpServletResponse resp) {
        long cityId = WebUtils.paramLong(req, "cityId", 0);
        long seriesId = WebUtils.paramLong(req, "seriesId", 0);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        long oClubId = WebUtils.paramLong(req, "oClubId", 0);
        GeliUser geliUser = GeliSession.getCurrentUser();
        if (geliUser == null) {
            errorMsg("请先登录", resp);
            return;
        }
        if (oClubId == 0) {
            errorMsg("请先填入官方车友会ID", resp);
            return;
        }
        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null) {
            errorMsg("官方车友会" + oClubId + "不存在", resp);
            return;
        }
        if (clubId > 0) { //单个入驻
            Club club = clubService.getClub(clubId);
            if (club == null) {
                errorMsg("自主车友会" + clubId + "不存在", resp);
                return;
            }
            if (oMemberService.findClubMember(clubId, oClubId) != null) {
                errorMsg("自主车友会" + clubId + "已经入驻过了", resp);
                return;
            }
            oMemberService.createClubMember(clubId, oClubId);
            String msg = String.format("自主车友会——%s[%s]成功入驻%s[%s]！", club.getName(), club.getClubId(), oClub.getName(), oClub.getoClubId());
            successMsg(resp, "list-oclub", msg, "closeCurrent");
        } else { //批量入驻
            if (cityId == 0 && seriesId == 0) {
                errorMsg("请至少填入（自主车友会或者车系或者城市）ID", resp);
                return;
            }
            int rs = oMemberService.batchCreateClubMember(0, seriesId, 0, cityId, oClubId);
            if (rs == 0) {
                errorMsg("没有满足条件的车友会可以入驻", resp);
                return;
            }
            String msg = String.format("%s个自主车友会成功入驻%s[%s]！", rs, oClub.getName(), oClub.getoClubId());
            successMsg(resp, "list-oclub", msg, "closeCurrent");
        }
    }
}
